<?php
/* 
 * $Id: vars_context.php 11 2010-11-24 22:10:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-24 22:10:53 +0000 (Wed, 24 Nov 2010) $
 * $Revision: 11 $
*/

namespace cmFly\view;
class vars_context implements \ArrayAccess,\Iterator {
    protected $data=Array();
    protected $my_data;
    /**
     *
     * @var vars_context
     */
    protected $parent;
    public function __construct(vars_context $parent=NULL) {
	if($parent) {
	    $this->data[]=$parent;
	    $this->parent=$parent;
	}
	$this->my_data=Array();
	$this->data[]=&$this->my_data;
    }
    public function seek ($position) {
	throw new \cmFly\system\exception('Can\'t seek from vars_context!');
    }
    public function current () {
	$current=&$this->get_current_array();
	if(is_object($current)) {
	    return $current->current();
	}
	return current($current);
    }
    public function next () {
	$current=&$this->get_current_array();
	if(is_object($current)) {
	    $next=$current->next();
	}
	else {
	    $next=next($current);
	}
	if($next!==FALSE) {
	    return $next;
	}
	//if(next($this->data)===$this->parent && isset($this->parent)) {
	next($this->data);
	//}
	try {
	    return $this->current();
	} catch(\Exception $e) {
	    return FALSE;
	}
    }
    public function key () {
	$current=&$this->get_current_array();
	if(is_object($current)) {
	    return $current->key();
	}
	return key($current);
    }
    public function valid () {
	try {
	    return $this->key()!==NULL;
	} catch(\Exception $e) {
	    return FALSE;
	}
    }
    public function rewind () {
	foreach($this->data as $k=>$v) {
	    reset($this->data[$k]);
	}
	return reset($this->data);
    }
    public function offsetExists ($offset) {
	return isset($this->my_data[$offset]);
    }
    public function offsetGet ($offset) {
	return $this->my_data[$offset];
    }
    public function offsetSet ($offset, $value) {
	$this->my_data[$offset]=$value;
	return $value;
    }
    public function offsetUnset ($offset) {
	unset($this->my_data[$offset]);
    }
    /**
     *
     * @return vars_context
     */
    public function create_layer() {
	$new_layer=new vars_context($this);
	//$this->data[]=$new_layer;
	return $new_layer;
    }
    protected function delete_layer(vars_context $context) {
	foreach($this->data as $k=>$v) {
	    if($v===$context) {
		unset($this->data[$k]);
		return;
	    }
	}
    }
    public function delete() {
	if($this->parent) {
	    return $this->parent->delete_layer($this);
	}
    }
    /**
     *
     * @return vars_context
     */
    protected function &get_current_array() {
	$key=key($this->data);
	if($key!==FALSE && isset($this->data[$key])) {
	    return $this->data[$key];
	}
	throw new \Exception('Current array is NULL!');
    }
}
